const db = require('../db/index')

//获取文章列表分类
exports.getArticleCates = (req, res) => {
    const sql = 'select * from ev_article_cate where is_delete=0 order by id asc;'
    db.query(sql, (error, results) => {
        if (error) return res.cc(error)
        res.send({
            status: 0,
            message: '获取文章分类列表成功！',
            data: results
        })
    })
}

exports.addArticleCates = (req, res) => {
    // res.send('ok')
    const sql = 'select * from ev_article_cate where name=? or alias=?;'
    db.query(sql, [req.body.name, req.body.alias], (error, results) => {
        if (error) return res.cc(error)
        if (results.length === 2) return res.cc('分类名称与别名被占用，请更换后重试！')
        if (results.length === 1 && results[0].name === req.body.name) return res.cc('分类名称被占用，请更换后重试！')
        if (results.length === 1 && results[0].alias === res.body.alias) return res.cc('分类别名被占用，请更换后重试！')

        const sql = 'insert into ev_article_cate set ?;'
        db.query(sql, { name: req.body.name, alias: req.body.alias, is_delete: 0 }, (err, result) => {
            if (err) return res.send(err)
            if (result.affectedRows !== 1) return res.cc('新增文章分类失败！')
            res.cc('新增文章分类成功！', 0)
        })
    })
}

exports.deleteCateById = (req,res)=>{
    const sql = 'update ev_article_cate set is_delete=1 where Id=?'
    db.query(sql,req.params.id,(error,results)=>{
        if(error) return res.cc(error)
        if(results.affectedRows !== 1) return res.cc('删除文章分类失败！')
        res.cc('删除文章分类成功！',0)
    })
}

exports.getArticleById = (req,res)=>{
    const sql = 'select * from ev_article_cate where id=?;'
    db.query(sql,req.params.id,(error,results)=>{
        if(error) return res.cc(error)
        if(results.length !== 1) return res.cc('获取文章分类失败！')
        res.send({
            status:0,
            message:'获取文章分类成功！',
            data:results
        })
    })
}

exports.updatecate = (req,res)=>{
    // res.send('ok')
    // console.log(req.body);
    const sql = 'select * from ev_article_cate where Id<>? and (name=? or alias=?);'
    db.query(sql,[req.body.Id,req.body.name,req.body.alias],(error,results)=>{
        if(error) return res.cc(error)
        if(results.length === 2)return res.cc('分类名称与别名被占用，请更换后重试！')
        if(results.length === 1 && results[0].name === req.body.name) return res.cc('分类名称被占用，请更正后重试！')
        if(results.length === 1 && results[0].alias === req.body.alias) return res.cc('分类别名被占用，请更正后重试！')

        const sql = 'update ev_article_cate set ? where Id=?;'
        db.query(sql,[req.body,req.body.Id],(err,results)=>{
            if(err) return res.cc(err)
            if(results.affectedRows !== 1) return res.cc('更新文章分类失败')
            res.cc('更新文章分类成功！',0)
        })
    })
}